#!/bin/bash

. $OPENARS_HOME/common/debug.h
. $OPENARS_HOME/common/functions.h

user=$USER_ARS
[ -z "$user" ] && user=$LOGNAME

>$OUTFILE

SUDO=/usr/local/bin/sudo

declare -a monthez

monthez=(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec)

CurYear=`date +%Y`
CurDay=`date +%d`
ICurMonth=`date +%m`
IPrevMonth=`expr $ICurMonth - 1|sed 's/^[0-9]$/0&/'`
SCurMonth=${monthez[`expr $ICurMonth - 1`]}
SPrevMonth=${monthez[`expr $ICurMonth - 2`]}
DaysCurMonth=`expr $CurDay - 0`
DaysPrevMonth=`expr 8 - $DaysCurMonth`
LatestDayPrevMonth=`cal $(expr $ICurMonth - 1) $CurYear | sed 1,2d | xargs echo | awk '{print $NF}'`

# $OUTFILE --> DB
function update_db() {
$ORACLE_HOME/bin/sqlplus >&2 -s /NOLOG << END
    WHENEVER SQLERROR EXIT SQL.SQLCODE
    set feedback off
    connect $CONNECT_ARS
    @"$OUTFILE"
    commit;
    exit;
END
    return $?
}


CreateGrepList ()
{
	Month=$1
	NumberOfDays=$2
	LatestDay=$3
	i=0
	if [ $GrepList ] ; then
		GrepList="$GrepList|$Month/$(expr $LatestDay - $i|sed 's/^[0-9]$/0&/')"
	else
		GrepList="$Month/$(expr $LatestDay - $i|sed 's/^[0-9]$/0&/')"
	fi
	i=`expr $i + 1`
	while [ $i -lt $NumberOfDays ] ; do
		GrepList="$GrepList|$Month/$(expr $LatestDay - $i|sed 's/^[0-9]$/0&/')"
		i=`expr $i + 1`
	done
}

srvlist=`get_hosts --os=Unix --control=YES`
INF "count hosts: `echo $srvlist | wc -w`"

	for server in $srvlist ; do

	( mkdir -p $TEMPDIR/data
	  result=""
	  SSH $user@$server "${SUDO} cp /var/adm/sulog ./ ; ${SUDO} chown $user ./sulog"
	  sftp $user@$server &>/dev/null << END
	    get ./sulog $TEMPDIR/data/$server
END
	) &
	done

wait

if [ "$CurDay" -gt 8 ] ; then
	CreateGrepList $ICurMonth 8 $CurDay
elif [ "$CurDay" -gt 1 ] && [ "$CurDay" -le 8 ] ; then
	CreateGrepList $ICurMonth $DaysCurMonth $CurDay
	CreateGrepList $IPrevMonth $DaysPrevMonth $LatestDayPrevMonth
elif [ "$CurDay" -eq 1 ] ; then
	CreateGrepList $IPrevMonth $DaysPrevMonth $LatestDayPrevMonth
fi
INF "GrepList = $GrepList"


cd $TEMPDIR/data

for server in *
do
	StrNumber="`cat $server|wc -l`"
	SuString=1
	while [ "${SuString}" ] ; do 
		SuString="$(cat $server | sed -n "${StrNumber}p" | egrep "$GrepList")"
		StrNumber=`expr $StrNumber - 1`
		if [ "`echo ${SuString}|grep "+"`" ] ; then
			DateTime="`echo $SuString|awk '{print$2,$3}'`"
			Terminal="`echo $SuString|awk '{print$5}'`"
			SourceUser="`echo $SuString|awk '{print$6}'|awk -F\- '{print $1}'`"
			DestUser="`echo $SuString|awk '{print$6}'|awk -F\- '{print $2}'`"
			printf "exec merge_su_logg('%s','%s','%s','%s',to_date('%s','MM/DD HH24:MI')); \n" $server $SourceUser $DestUser $Terminal "$DateTime" >> $OUTFILE
#			echo $DateTime $Terminal  $SourceUser $DestUser
			
		fi
	done
done

update_db
if [ "$?" -ne 0 ]; then
    ERR "error function update_db()"
    exit 1
fi

exit 0;
